<template>
  <el-main>
    <!-- 搜索栏-->
    <el-form
      ref="listParam"
      :model="listParam"
      :inline="true"
      size="small"
    >
      <el-form-item label="">
        <el-input v-model="listParam.roleName" placeholder="请输入角色的名称" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="searchBtn">搜索</el-button>
        <el-button icon="el-icon-close" style="color: #ff7670;" @click="resetBtn">重置</el-button>
        <el-button v-permission="['sys:sysRoleList:add']" type="primary" icon="el-icon-plus" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="tableData" border stripe :height="tableHeight">
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="roleType" label="角色类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.roleType === '1'" type="danger">系统用户</el-tag>
          <el-tag v-if="scope.row.roleType === '2'" type="success">学生</el-tag>
          <el-tag v-if="scope.row.roleType === '3'" type="warning">教师</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="$checkPermission(['sys:sysRoleList:edit', 'sys:sysRoleList:assign', 'sys:sysRoleList:delete'])" label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button v-permission="['sys:sysRoleList:assign']" type="primary" size="small" icon="el-icon-edit" @click="assignBtn(scope.row)">分配权限</el-button>
          <el-button v-permission="['sys:sysRoleList:edit']" type="primary" size="small" icon="el-icon-edit" @click="editBtn(scope.row)">编辑</el-button>
          <el-button v-permission="['sys:sysRoleList:delete']" type="danger" size="small" icon="el-icon-delete" @click="deleteBtn(scope.row)">删除</el-button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      :current-page.sync="listParam.currentPage"
      :page-sizes="[10, 20, 40, 80, 100]"
      :page-size="listParam.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listParam.total"
      background
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <sys-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      :width="dialog.width"
      :height="dialog.height"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form ref="addModel" :model="addModel" :rules="rules" label-width="80px" size="small">
          <el-row>
            <el-col :span="12" offset="0">
              <el-form-item prop="roleName" label="角色名称">
                <el-input v-model="addModel.roleName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" offset="0">
              <el-form-item prop="roleType" label="角色类型">
                <el-select v-model="addModel.roleType" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" offset="0">
              <el-form-item label="角色备注">
                <el-input v-model="addModel.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </div>
    </sys-dialog>
    <!-- 分配权限的弹窗 -->
    <sys-dialog
      :title="assignDialog.title"
      :visible.sync="assignDialog.visible"
      :width="assignDialog.width"
      :height="assignDialog.height"
      @onClose="assignClose"
      @onConfirm="assignConfirm"
    >
      <div slot="content">
        <el-tree
          ref="assginTreeData"
          :data="assginTreeData"
          show-checkbox
          default-expand-all
          :default-checked-keys="assignTreeChecked"
          node-key="menuId"
          empty-text="暂无数据"
          :props="defaultProps"
        />

      </div>
    </sys-dialog>

  </el-main>

</template>

<script>
import { addRoleApi, assignRoleApi, deleteRoleApi, editRoleApi, getRoleListApi, saveAssignRoleApi } from '@/api/role'
import SysDialog from '@/components/dialog/SysDialog.vue'
import { getUserId } from '@/utils/auth'
export default {
  components: { SysDialog },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // 角色id
      roleId: '',
      // 树数据
      assginTreeData: [],
      // 角色原来权限
      assignTreeChecked: [],
      // 定义分配角色弹框属性
      assignDialog: {
        title: '',
        height: 450,
        width: 400,
        visible: false
      },
      // 角色类型
      options: [
        {
          value: '1',
          label: '系统管理员'
        },
        {
          value: '2',
          label: '学生'
        },
        {
          value: '3',
          label: '教师'
        }

      ],
      // 表单验证
      rules: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          trigge: 'blur'
        }],
        roleType: [{
          required: true,
          message: '请选择角色类型',
          trigge: 'blur'
        }]
      },
      // 新增表单绑定数据
      addModel: {
        type: '', // 0:新增，1:编辑
        roleId: '',
        roleType: '',
        roleName: '',
        remark: ''
      },
      // 弹窗属性
      dialog: {
        title: '',
        visible: false,
        width: 630,
        height: 150
      },
      // 表格高度
      tableHeight: 0,
      // 搜索栏数据
      listParam: {
        roleName: '',
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表格数据
      tableData: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 220
    })
  },
  created() {
    this.getList()
  },
  methods: {
    assignClose() {
      this.assignDialog.visible = false
    },
    async assignConfirm() {
      const ids = this.$refs.assginTreeData.getCheckedKeys().concat(this.$refs.assginTreeData.getHalfCheckedKeys())
      // console.log(ids)
      const param = {
        roleId: this.roleId,
        menuIds: ids
      }
      const res = await saveAssignRoleApi(param)
      if (res && res.code === 200) {
        this.$message.success(res.msg)
        this.assignDialog.visible = false
      }
    },
    async assignBtn(row) {
      // console.log(row)
      this.roleId = row.roleId
      this.assignDialog.title = '为[' + row.roleName + ']分配权限'
      // 获取权限树数据
      const param = {
        roleId: row.roleId,
        userId: getUserId()
      }
      const res = await assignRoleApi(param)
      if (res || res.code === 200) {
        console.log(res)
        this.assginTreeData = res.data.sysMenuList
        this.assignTreeChecked = res.data.checkList
        // 过滤回显数据
        if (this.assignTreeChecked.length > 0) {
          const newArr = []
          this.assignTreeChecked.forEach((item) => {
            this.checked(item, this.assginTreeData, newArr)
          })
          this.assignTreeChecked = newArr
        }
      }
      this.assignDialog.visible = true
    },
    // 过滤工具
    checked(id, data, newArr) {
      data.forEach((item) => {
        if (item.menuId === id) {
          if (item.children && item.children.length === 0) {
            newArr.push(item.menuId)
          }
        } else {
          // 有下级的时候继续查找
          if (item.children && item.children.length !== 0) {
            // 递归算法
            this.checked(id, item.children, newArr)
          }
        }
      })
    },
    onClose() {
      this.dialog.visible = false
    },
    onConfirm() {
      // 表单验证
      this.$refs.addModel.validate(async(valid) => {
        if (valid) {
          let res = null
          if (this.addModel.type === '0') {
            res = await addRoleApi(this.addModel)
          } else {
            res = await editRoleApi(this.addModel)
          }
          if (res && res.code === 200) {
            // 信息提示
            this.$message({
              type: 'success',
              message: res.msg
            })
            // 刷新列表
            this.getList()
            this.dialog.visible = false
          }
        }
      })
    },
    async getList() {
      const res = await getRoleListApi(this.listParam)
      if (res && res.code === 200) {
        this.tableData = res.data.records
        this.listParam.total = res.data.total
      }
    },
    // 页数改变时触发
    currentChange(val) {
      this.listParam.currentPage = val
      this.getList()
    },
    // 也容量改变时触发
    sizeChange(val) {
      this.listParam.pageSize = val
      this.getList
    },
    // 新增按钮
    addBtn() {
      this.dialog.title = '新增角色'
      // 清空表单
      // this.$resetForm('addModel', this.addModel)
      this.dialog.visible = true
      // 清空验证与数据
      if (this.$refs.addModel !== undefined) {
        this.$refs.addModel.resetFields()
        this.$emptyData(this.addModel)
      }
      this.addModel.type = '0'
    },
    // 搜索按钮
    searchBtn() {
      this.getList()
    },
    // 重置按钮
    resetBtn() {
      this.listParam.roleName = ''
      this.getList()
    },
    // 编辑按钮
    editBtn(row) {
      // 设置表单属性
      this.dialog.title = '编辑表单'
      this.dialog.type = '1'
      // this.$resetForm('addModel', this.addModel)
      // 清空验证与数据
      if (this.$refs.addModel !== undefined) {
        this.$refs.addModel.resetFields()
        this.$emptyData(this.addModel)
      }
      // 把当前要编辑的数据复制到表单绑定的数据域
      this.$objCopy(row, this.addModel)
      this.dialog.visible = true
    },
    // 删除按钮
    async deleteBtn(row) {
      const confirm = await this.$myconfirm('确定删除该数据吗？')
      if (confirm) {
        const res = await deleteRoleApi({ roleId: row.roleId })
        if (res && res.code === 200) {
          // 信息提示
          this.$message({
            type: 'success',
            message: res.msg
          })
          // 刷新列表
          this.getList()
        }
      }
    }
  }

}
</script>

<style lang="scss" scoped>

</style>
